<?php


namespace app\common\library;


use GuzzleHttp\Client;
use think\Db;

class Amap
{
    public $error = '';
    protected $config = [];
    protected static $instance;

    public function __construct($options = [])
    {
        $this->config['webamapkey'] = Db::name('config')->where('name','webamapkey')->value('value');
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }

    /**
     * 单例
     * @param array $options 参数
     * @return Amap
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }

        return self::$instance;
    }

    public function regeo($lnt, $lat)
    {
        $uri = 'https://restapi.amap.com/v3/geocode/regeo';
        $query = [
            'location' => $lnt . ',' . $lat,
            'key' => $this->config['webamapkey'],
        ];
        $response = $this->request('GET', $uri, compact('query'));
        return json_decode($response, true);
    }

    public function ip2Address($ip)
    {
        $uri = 'https://restapi.amap.com/v3/ip';
        $query = [
            'ip' => $ip,
            'key' => $this->config['webamapkey'],
        ];
        $response = $this->request('GET', $uri, compact('query'));
        return json_decode($response, true);
    }

    private function request($method, $uri, $options = [] )
    {
        $client = new Client([
            'http_errors' => false,
            'verify' => false,
        ]);
        $response = $client->request($method, $uri, $options);
        return (string)$response->getBody();
    }
}